package com.lwy.jwt;

import com.lwy.security.UserConfig;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private UserConfig userConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(JWTUtils.HEAD);

        //包含token
        if(null!=token){
            //解析token
            Claims parse = JWTUtils.parse(token);
            String username = JWTUtils.getUsername(token);
            boolean expiration = JWTUtils.isExpiration(token);
            if (expiration) {
                if(null!=parse&& null!=username){
                    SecurityContextHolder.getContext().setAuthentication(getAuthentication(username));
                }
            }
        }else{
            String yk = "游客";
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(yk));
        }
        filterChain.doFilter(request,response);
    }

    protected UsernamePasswordAuthenticationToken getAuthentication(String username){
        UserDetails userDetails = userConfig.loadUserByUsername(username);
        return new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
    }
}
